<template>
  <div>
    <h1>Bar Chart with D3.js in Vue</h1>
    <div ref="chart" style="border: 1px solid;width: 430px;height: 152px;margin: auto;"></div>
  </div>
</template>

<script>
import * as d3 from "d3"
import { WaveView } from "./Wave/index"
// import { WaveView } from "./Wave/index1"

import { mockData } from "../mockData"
export default {
  data() {
    return {
      chartData: [], // 用于存储动态数据的数组

      queue: [],
      lastX: 0,
      lastY: 0,
      currentX: 0,
      currentY: 0,

      newData: [
        ...mockData[0].wav,
        ...mockData[0].wav,
        ...mockData[0].wav,
        ...mockData[0].wav,
        ...mockData[0].wav,
        ...mockData[0].wav,
        ...mockData[0].wav,
        ...mockData[0].wav,
        ...mockData[0].wav,
        ...mockData[0].wav,
      ],
      context: null,
    }
  },
  mounted() {
    const wave = new WaveView({
      el: this.$refs.chart,
      frameSize: mockData.length,
      step: 0,
      strokeStyle: "#00ff00",
    })
    setInterval(() => {
      wave.addData(mockData[0].wav)
    }, 1000)
    // this.initializeChart()
    // this.startDataSimulation()
  },
  methods: {
    initializeChart() {
      // 初始化心电图
      const canvas = d3
        .select(this.$refs.chart)
        .append("canvas")
        .attr("width", 430)
        .attr("height", 152)
        .node()

      this.context = canvas.getContext("2d")
    },
    startDataSimulation() {
      this.chartData = [
        ...mockData[0].wav,
        ...mockData[0].wav,
        ...mockData[0].wav,
        ...mockData[0].wav,
        ...mockData[0].wav,
        ...mockData[0].wav,
        ...mockData[0].wav,
        ...mockData[0].wav,
        ...mockData[0].wav,
      ]
      this.updateChart()
    },
    generateData() {
      this.chartData.push(...this.newData.splice(0, 50))
      const startIndex = this.chartData.length - 4000
      this.chartData = this.chartData.slice(startIndex)
      console.log("this.chartData:", this.chartData)
    },
    updateChart() {
      // 更新心电图
      const xScale = d3.scaleLinear().domain([0, 6000]).range([0, 430])

      const yScale = d3
        .scaleLinear()
        .domain([-d3.max(this.chartData) - 100, d3.max(this.chartData) + 100])
        .range([152 * 0.8, 30])

      // 画线
      this.context.beginPath()
      this.context.moveTo(xScale(0), yScale(this.chartData[0]))

      for (var i = 1; i < this.chartData.length; i++) {
        // this.context.clearRect(0, 0, 20, 152)
        this.context.lineTo(xScale(i), yScale(this.chartData[i]))
      }

      this.context.lineWidth = 1
      this.context.strokeStyle = "red"
      this.context.stroke()
    },
  },
}
</script>
